import 'package:flutter/material.dart';
import '../../api/search_service.dart';
import '../../models/pet.dart';
import '../../models/post.dart';
import '../../models/user.dart';
import '../../models/video.dart';
import '../../config/app_theme.dart';
import '../adoption/pet_detail_screen.dart';
import '../community/post_detail_screen.dart';
import '../videos/video_detail_screen.dart';

class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> with SingleTickerProviderStateMixin {
  final SearchService _searchService = SearchService();
  final TextEditingController _searchController = TextEditingController();
  late TabController _tabController;
  SearchResult _searchResult = SearchResult();
  List<String> _searchHistory = [];
  bool _isLoading = false;
  bool _isSearching = false;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 5, vsync: this);
    _loadSearchHistory();
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    super.dispose();
  }
  
  Future<void> _loadSearchHistory() async {
    try {
      final history = await _searchService.getSearchHistory();
      setState(() {
        _searchHistory = history;
      });
    } catch (e) {
      print('Error loading search history: $e');
    }
  }
  
  Future<void> _search(String query) async {
    if (query.isEmpty) {
      return;
    }
    
    setState(() {
      _isLoading = true;
      _isSearching = true;
    });
    
    try {
      // 保存搜索历史
      await _searchService.saveSearchQuery(query);
      // 执行搜索
      final result = await _searchService.search(query);
      
      setState(() {
        _searchResult = result;
        _isLoading = false;
      });
      
      // 重新加载搜索历史
      _loadSearchHistory();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error searching: $e');
    }
  }
  
  Future<void> _clearSearchHistory() async {
    try {
      final success = await _searchService.clearSearchHistory();
      
      if (success) {
        setState(() {
          _searchHistory = [];
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('搜索历史已清空'))
        );
      }
    } catch (e) {
      print('Error clearing search history: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('清空搜索历史失败，请稍后再试'))
      );
    }
  }
  
  void _onSearchSubmitted(String value) {
    _search(value);
  }
  
  void _onHistoryItemTap(String query) {
    _searchController.text = query;
    _search(query);
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: _searchController,
          decoration: InputDecoration(
            hintText: '搜索宠物、帖子、视频或用户',
            border: InputBorder.none,
            hintStyle: TextStyle(color: Colors.grey),
          ),
          style: TextStyle(fontSize: 16),
          textInputAction: TextInputAction.search,
          onSubmitted: _onSearchSubmitted,
        ),
        actions: [
          if (_searchController.text.isNotEmpty)
            IconButton(
              icon: Icon(Icons.clear),
              onPressed: () {
                _searchController.clear();
                setState(() {
                  _isSearching = false;
                  _searchResult = SearchResult();
                });
              },
            ),
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () => _search(_searchController.text),
          ),
        ],
        bottom: _isSearching ? TabBar(
          controller: _tabController,
          isScrollable: true,
          tabs: [
            Tab(text: '全部'),
            Tab(text: '宠物 (${_searchResult.pets.length})'),
            Tab(text: '帖子 (${_searchResult.posts.length})'),
            Tab(text: '视频 (${_searchResult.videos.length})'),
            Tab(text: '用户 (${_searchResult.users.length})'),
          ],
        ) : null,
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : !_isSearching
              ? _buildSearchHistory()
              : _searchResult.isEmpty
                  ? _buildEmptyResult()
                  : TabBarView(
                      controller: _tabController,
                      children: [
                        _buildAllResults(),
                        _buildPetResults(),
                        _buildPostResults(),
                        _buildVideoResults(),
                        _buildUserResults(),
                      ],
                    ),
    );
  }
  
  Widget _buildSearchHistory() {
    if (_searchHistory.isEmpty) {
      return Center(
        child: Text(
          '暂无搜索历史',
          style: TextStyle(color: Colors.grey[600]),
        ),
      );
    }
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '搜索历史',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
              GestureDetector(
                onTap: _clearSearchHistory,
                child: Text(
                  '清空',
                  style: TextStyle(
                    color: AppTheme.primaryColor,
                    fontSize: 14,
                  ),
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _searchHistory.length,
            itemBuilder: (context, index) {
              return ListTile(
                leading: Icon(Icons.history, color: Colors.grey),
                title: Text(_searchHistory[index]),
                trailing: Icon(Icons.arrow_forward_ios, size: 16),
                onTap: () => _onHistoryItemTap(_searchHistory[index]),
              );
            },
          ),
        ),
      ],
    );
  }
  
  Widget _buildEmptyResult() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search_off,
            size: 64,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16),
          Text(
            '未找到相关结果',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8),
          Text(
            '尝试使用其他关键词搜索',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildAllResults() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (_searchResult.pets.isNotEmpty) ...[
            _buildSectionHeader('宠物', onSeeAllPressed: () {
              _tabController.animateTo(1);
            }),
            SizedBox(
              height: 220,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: min(_searchResult.pets.length, 5),
                itemBuilder: (context, index) {
                  return _buildPetCard(_searchResult.pets[index]);
                },
              ),
            ),
          ],
          
          if (_searchResult.posts.isNotEmpty) ...[
            _buildSectionHeader('帖子', onSeeAllPressed: () {
              _tabController.animateTo(2);
            }),
            ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: min(_searchResult.posts.length, 3),
              itemBuilder: (context, index) {
                return _buildPostItem(_searchResult.posts[index]);
              },
            ),
          ],
          
          if (_searchResult.videos.isNotEmpty) ...[
            _buildSectionHeader('视频', onSeeAllPressed: () {
              _tabController.animateTo(3);
            }),
            SizedBox(
              height: 160,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: min(_searchResult.videos.length, 5),
                itemBuilder: (context, index) {
                  return _buildVideoCard(_searchResult.videos[index]);
                },
              ),
            ),
          ],
          
          if (_searchResult.users.isNotEmpty) ...[
            _buildSectionHeader('用户', onSeeAllPressed: () {
              _tabController.animateTo(4);
            }),
            ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: min(_searchResult.users.length, 3),
              itemBuilder: (context, index) {
                return _buildUserItem(_searchResult.users[index]);
              },
            ),
          ],
          
          SizedBox(height: 16),
        ],
      ),
    );
  }
  
  Widget _buildPetResults() {
    if (_searchResult.pets.isEmpty) {
      return _buildEmptyView('未找到相关宠物');
    }
    
    return GridView.builder(
      padding: EdgeInsets.all(8.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 8.0,
        mainAxisSpacing: 8.0,
        childAspectRatio: 0.75,
      ),
      itemCount: _searchResult.pets.length,
      itemBuilder: (context, index) {
        return _buildPetGridItem(_searchResult.pets[index]);
      },
    );
  }
  
  Widget _buildPostResults() {
    if (_searchResult.posts.isEmpty) {
      return _buildEmptyView('未找到相关帖子');
    }
    
    return ListView.builder(
      itemCount: _searchResult.posts.length,
      itemBuilder: (context, index) {
        return _buildPostItem(_searchResult.posts[index]);
      },
    );
  }
  
  Widget _buildVideoResults() {
    if (_searchResult.videos.isEmpty) {
      return _buildEmptyView('未找到相关视频');
    }
    
    return GridView.builder(
      padding: EdgeInsets.all(8.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 8.0,
        mainAxisSpacing: 8.0,
        childAspectRatio: 0.6,
      ),
      itemCount: _searchResult.videos.length,
      itemBuilder: (context, index) {
        return _buildVideoGridItem(_searchResult.videos[index]);
      },
    );
  }
  
  Widget _buildUserResults() {
    if (_searchResult.users.isEmpty) {
      return _buildEmptyView('未找到相关用户');
    }
    
    return ListView.builder(
      itemCount: _searchResult.users.length,
      itemBuilder: (context, index) {
        return _buildUserItem(_searchResult.users[index]);
      },
    );
  }
  
  Widget _buildEmptyView(String message) {
    return Center(
      child: Text(
        message,
        style: TextStyle(color: Colors.grey[600]),
      ),
    );
  }
  
  Widget _buildSectionHeader(String title, {required VoidCallback onSeeAllPressed}) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          GestureDetector(
            onTap: onSeeAllPressed,
            child: Text(
              '查看全部',
              style: TextStyle(
                color: AppTheme.primaryColor,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildPetCard(Pet pet) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PetDetailScreen(pet: pet),
          ),
        );
      },
      child: Container(
        width: 150,
        margin: EdgeInsets.only(left: 16, right: 8, bottom: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
              child: Image.network(
                pet.images.first,
                height: 120,
                width: double.infinity,
                fit: BoxFit.cover,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    pet.name,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  SizedBox(height: 4),
                  Text(
                    '${pet.breed} · ${pet.age}岁 · ${pet.gender}',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                  SizedBox(height: 8),
                  Text(
                    pet.location,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[700],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildPetGridItem(Pet pet) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PetDetailScreen(pet: pet),
          ),
        );
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
              child: Image.network(
                pet.images.first,
                height: 120,
                width: double.infinity,
                fit: BoxFit.cover,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    pet.name,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 14,
                    ),
                  ),
                  SizedBox(height: 4),
                  Text(
                    '${pet.breed} · ${pet.age}岁',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                  SizedBox(height: 4),
                  Row(
                    children: [
                      CircleAvatar(
                        radius: 8,
                        backgroundImage: NetworkImage(pet.ownerAvatar),
                      ),
                      SizedBox(width: 4),
                      Expanded(
                        child: Text(
                          pet.ownerName,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[700],
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildPostItem(Post post) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PostDetailScreen(post: post),
          ),
        );
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 16,
                    backgroundImage: NetworkImage(post.userAvatar),
                  ),
                  SizedBox(width: 8),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        post.userName,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                      Text(
                        _formatDate(post.createdAt),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12.0),
              child: Text(
                post.title,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Text(
                post.content,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 14),
              ),
            ),
            if (post.images.isNotEmpty)
              Image.network(
                post.images.first,
                height: 150,
                width: double.infinity,
                fit: BoxFit.cover,
              ),
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Row(
                children: [
                  Icon(Icons.favorite_border, size: 18, color: Colors.grey),
                  SizedBox(width: 4),
                  Text(
                    post.likes.toString(),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey,
                    ),
                  ),
                  SizedBox(width: 16),
                  Icon(Icons.comment, size: 18, color: Colors.grey),
                  SizedBox(width: 4),
                  Text(
                    post.comments.toString(),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildVideoCard(Video video) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => VideoDetailScreen(video: video),
          ),
        );
      },
      child: Container(
        width: 200,
        margin: EdgeInsets.only(left: 16, right: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.network(
                    video.coverUrl,
                    height: 110,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                  bottom: 8,
                  right: 8,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.7),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      _formatDuration(video.duration),
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Icon(
                    Icons.play_circle_outline,
                    color: Colors.white.withOpacity(0.8),
                    size: 40,
                  ),
                ),
              ],
            ),
            SizedBox(height: 8),
            Text(
              video.title,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 14,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildVideoGridItem(Video video) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => VideoDetailScreen(video: video),
          ),
        );
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
                  child: Image.network(
                    video.coverUrl,
                    height: 110,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                  bottom: 8,
                  right: 8,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.7),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      _formatDuration(video.duration),
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Icon(
                    Icons.play_circle_outline,
                    color: Colors.white.withOpacity(0.8),
                    size: 40,
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    video.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 14,
                    ),
                  ),
                  SizedBox(height: 8),
                  Row(
                    children: [
                      CircleAvatar(
                        radius: 10,
                        backgroundImage: NetworkImage(video.userAvatar),
                      ),
                      SizedBox(width: 4),
                      Expanded(
                        child: Text(
                          video.userName,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 4),
                  Text(
                    '${_formatNumber(video.views)}次观看',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildUserItem(User user) {
    return ListTile(
      leading: CircleAvatar(
        backgroundImage: NetworkImage(user.avatar),
      ),
      title: Text(
        user.username,
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
      subtitle: user.bio != null && user.bio!.isNotEmpty
          ? Text(
              user.bio!,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            )
          : null,
      trailing: TextButton(
        onPressed: () {
          // 切换关注状态
          // TODO: 实现关注功能
        },
        style: TextButton.styleFrom(
          backgroundColor: AppTheme.primaryColor,
          primary: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          padding: EdgeInsets.symmetric(horizontal: 16.0),
          minimumSize: Size(80, 32),
        ),
        child: Text('关注'),
      ),
      onTap: () {
        // 导航到用户资料页
        // TODO: 实现用户资料页
      },
    );
  }
  
  String _formatDate(DateTime date) {
    return '${date.month}月${date.day}日';
  }
  
  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '$minutes:${remainingSeconds.toString().padLeft(2, '0')}';
  }
  
  String _formatNumber(int number) {
    if (number >= 10000) {
      return '${(number / 10000).toStringAsFixed(1)}万';
    } else if (number >= 1000) {
      return '${(number / 1000).toStringAsFixed(1)}千';
    }
    return number.toString();
  }
  
  int min(int a, int b) {
    return a < b ? a : b;
  }
} 